package util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;

import com.sun.corba.se.spi.orbutil.threadpool.Work;
import com.sun.javafx.iio.common.ImageDescriptor;
import com.sun.org.apache.bcel.internal.generic.NEW;

/**
 * 向对应的socket流发送文件
 */
public class FileSender {

	private String fileName = "";
	private String ip = "";
	private int port = 8821;
	private HashMap<String, String> map;

	public FileSender(String ip, int port, String fileName, HashMap<String, String> map) {
		super();
		this.ip = ip;
		this.port = port;
		this.fileName = fileName;
		this.map = map;
	}

	/**
	 * @描述：传送文件
	 * @时间：上午9:19:19
	 * @开发者：稀饭 
	 * @测试：通過
	 * @param 文件地址以及名字
	 *            接收方的ip 接收方的监控ip
	 * @return 0证明无须操作 其他证明需要重新录入文件
	 */
	private long sendFile() throws IOException {
		File file = new File(fileName);
		if (map.get(fileName) != null && map.get(fileName).equals(file.length() + "")) {
			return 0;
		}
		Socket socket = null;
		try {
			socket = new Socket(ip, port);
		} catch (UnknownHostException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		DataOutputStream dos = null;
		try {
			dos = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		// 传送的文件名字
		dos.writeUTF(fileName + "");
		dos.writeLong(file.length());
		map.remove(fileName);
		map.put(fileName, file.length()+"");
		dos.flush();
		dos.flush();
		DataInputStream dis = null;
		try {
			dis = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		int buffferSize = 1024;
		byte[] bufArray = new byte[buffferSize];
		try {
			while (true) {
				int read = 0;
				if (dis != null) {
					read = dis.read(bufArray);
				}
				if (read == -1) {
					break;
				}
				dos.write(bufArray, 0, read);
			}
			dos.flush();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			// 关闭所有连接
			try {
				if (dos != null)
					dos.close();
			} catch (IOException e) {
			}
			try {
				if (dis != null)
					dis.close();
			} catch (IOException e) {
			}
			try {
				if (socket != null)
					socket.close();
			} catch (IOException e) {
			}
		}
		return file.length();
	}

	/**
	 * @描述：主要功能入口
	 * @时间：下午2:48:48
	 * @开发者：稀饭 @测试：通过
	 * @param
	 * @return
	 */
	public long work() {
		try {
			return sendFile();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return -1;
	}
}
